package com.ktjy.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.UserDTO;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ISysUserService;
import com.ktjy.service.impl.SysUserServiceImpl;
import com.ktjy.utils.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-07-28
 */
@RestController
@RequestMapping("/api/sys/user")
@Tag(name = "用户模块")
public class SysUserController {
    Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Resource
    ISysUserService sysUserService;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPerm('system:user:list')")
    @Operation(summary = "用户列表接口")
    public AjaxResult list(UserDTO userDTO,
                           @Parameter(description = "页码数") @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                           @Parameter(description = "每页显示条数") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        IPage<SysUser> page = sysUserService.findPage(userDTO, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    @PostMapping("/save")
    @PreAuthorize("@ss.hasPerm('system:user:add')")
    @Operation(summary = "用户保存接口")
    public AjaxResult saveOrUpdate(@RequestBody SysUser sysUser) {
        try {
            sysUserService.saveOrUpdateUser(sysUser);
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            log.error("SysUserController中saveOrUpdate方法执行报错的。", e);
        }
        return AjaxResult.error("保存失败");
    }

    @PutMapping("/resetPwd")
    @PreAuthorize("@ss.hasPerm('system:user:resetPwd')")
    @Operation(summary = "用户重置密码接口")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        try {
            boolean ok = sysUserService.updateById(user);
            if (ok) {
                return AjaxResult.success("重置密码成功");
            }
        } catch (Exception e) {
            log.error("SysUserController中resetPwd方法执行报错的。", e);
        }
        return AjaxResult.error("重置密码失败");
    }

    @GetMapping("/view/{id}")
    @PreAuthorize("@ss.hasPerm('system:user:query')")
    @Operation(summary = "用户详情接口")
    public AjaxResult view(@PathVariable("id") Long id) {
        //查询用户详情
        try {
            SysUser sysUser = sysUserService.findUser(id);
            if (sysUser != null) {
                return AjaxResult.success(sysUser);
            }
        } catch (Exception e) {
            log.error("SysUserController中view方法执行报错的。", e);
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/del/{id}")
    @PreAuthorize("@ss.hasPerm('system:user:remove')")
    @Operation(summary = "用户删除接口")
    public AjaxResult del(@PathVariable("id") Long id) {
        try {
            sysUserService.deleteUser(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("SysUserController中del方法执行报错的。", e);
        }
        return AjaxResult.error("删除失败");
    }

    @GetMapping("/checkNameUnique")
    @Operation(summary = "用户名称唯一性校验接口")
    public AjaxResult checkNameUnique(@RequestParam("name") String name) {
        try {
            boolean ok = sysUserService.checkNameUnique(name);
            if (!ok) {//数据库不存在该账号
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.error("SysUserController中checkNameUnique方法执行报错的。", e);
        }
        return AjaxResult.error();
    }

    @GetMapping("/export")
    @Operation(summary = "用户导出接口")
    public void ecport(UserDTO userDTO, HttpServletResponse response) {
        //1.查询需要导出的数据
        List<SysUser> list = sysUserService.findList(userDTO);
        //得到一个excel文件

        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("用户数据");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, SysUser.class, list);
        //输出流输出给浏览器
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = null;
        try {
            //设置下载文件名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息表", "UTF-8") + ".xlsx");
            out = response.getOutputStream();
            workbook.write(out);
        } catch (Exception e) {
            log.error("SysUserController中ecport方法执行报错的。", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    log.error("SysUserController中ecport方法关闭流报错的。", e);
                }
            }
        }
    }
    @PostMapping("/import")
    public AjaxResult importExcel(MultipartFile  file) {
        //解析excel中的数据得到用户对象
        List<SysUser>list= sysUserService.importExcel(file);
        //将用户对象存储到数据库
        boolean ok = sysUserService.saveBatch(list);
        if (ok) {
            return AjaxResult.success("导入成功");
        }
        return AjaxResult.error("导入失败");
    }
}
